﻿using Shop.Common;
using Shop.Implementation.Customer;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;

namespace Shop.Implementation.SO
{
    public class ISO_V1 : Interface.SO.ISO
    {
        #region 获取订单列表（我的订单调用）

        public override Dictionary<string, object> GetList(int idcus)
        {
            NameValueCollection nv = System.Web.HttpContext.Current.Request.QueryString;
            string token = nv["token"].GetVal_String();
            int iRowS = nv["iRowS"].GetVal_Int();
            int iRowE = nv["iRowE"].GetVal_Int();

            #region 2、确认行数的逻辑是否正确，每次传递的行数不能大于10；

            if (iRowE < iRowS || iRowE > iRowS + 10)
            {
                return Common.ReturnValue.Get("行数不正确，系统退出", false);
            }

            #endregion 2、确认行数的逻辑是否正确，每次传递的行数不能大于10；

            DataTable dtmain;
            DataTable dtdetail;

            #region 3、获取客户所有订单ID，从商城订单表SOPre，并且按日期排序，保存到临时表；

            GetSOData(idcus, iRowS, iRowE, out dtmain, out dtdetail);

            #endregion 3、获取客户所有订单ID，从商城订单表SOPre，并且按日期排序，保存到临时表；

            #region 6、拼凑返回的Dictionary对象，明细数据需要包含在主表数据的里面；

            Dictionary<string, object> dic = Common.ReturnValue.Get("success", true);
            int ID;
            List<object> list = new List<object>();
            for (int i = 0; i < dtmain.Rows.Count; i++)
            {
                Dictionary<string, object> dicmain = new Dictionary<string, object>();
                for (int j = 0; j < dtmain.Columns.Count; j++)
                {
                    dicmain.Add(dtmain.Columns[j].ColumnName, dtmain.Rows[i][j]);
                }
                ID = dtmain.Rows[i]["ID"].GetVal_Int();
                DataRow[] dtrs = dtdetail.Select("ID=" + ID.ToString(), "autoid");

                List<object> listdetail = new List<object>();
                for (int k = 0; k < dtrs.Length; k++)
                {
                    Dictionary<string, object> dicdetail = new Dictionary<string, object>();
                    for (int j = 0; j < dtdetail.Columns.Count; j++)
                    {
                        dicdetail.Add(dtdetail.Columns[j].ColumnName, dtrs[k][j]);
                    }
                    listdetail.Add(dicdetail);
                }
                dicmain.Add("sodetail", listdetail);
                list.Add(dicmain);
            }
            dic.Add("so", list);
            return dic;

            #endregion 6、拼凑返回的Dictionary对象，明细数据需要包含在主表数据的里面；
        }

        private void GetSOData(int idcus, int irows, int irowe, out DataTable _dtmain, out DataTable _dtdetail)
        {
            using (SqlConnection cn = new SqlConnection(Common.HandleSQL.cConnstr))
            {
                try
                {
                    #region 3、获取客户所有订单ID，从商城订单表SOPre，并且按日期排序，保存到临时表；

                    SqlCommand cncmd = new SqlCommand();
                    cncmd.Connection = cn;
                    cn.Open();
                    string cmdsql = "if(object_id('tempdb..#tpo') is not null) drop table #tpo";
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();
                    cmdsql = string.Format(@"select row_number() over (order by dDate desc) as rowno,id into #tpo from SOPre (nolock)
                    where IDCus={0} order by row_number() over (order by dDate desc)", idcus);
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();

                    #endregion 3、获取客户所有订单ID，从商城订单表SOPre，并且按日期排序，保存到临时表；

                    #region 4、删掉不属于此次提取的行数；

                    cmdsql = string.Format("delete from #tpo where rowno<{0} or rowno>{1}", irows, irowe);
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();

                    #endregion 4、删掉不属于此次提取的行数；

                    cmdsql = "if(object_id('tempdb..#tpo1') is not null) drop table #tpo1";
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();

                    #region 5、获取订单主表与订单明细表的所有数据（ID属于3步取出的临时表）；

                    cmdsql = @"select id,SUM(iNum) as iNum,sum(iQuantity) as iQuantity, cast(SUM(iSum) as decimal(20,2)) as iSum into #tpo1 from  SODetailPre (nolock)
                    where id in (select id from #tpo) group by id";
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();

                    cmdsql = @"select so.ID,customer.cMobile,customer.storeName,so.cSOCode,so.cSHR,so.cSHMobile,so.cSHDZ,convert(nvarchar,so.dDate,23) as dDate,so.dPSTimeStart,so.dPSTimeEnd,
                    detail.iQuantity,detail.iSum,so.iStatus,case iStatus ";
                    DataTable dtyh = getSoStatus();
                    for (int i = 0; i < dtyh.Rows.Count; i++)
                    {
                        cmdsql += string.Format(" when {0} then '{1}' ", dtyh.Rows[i]["iStatus"], dtyh.Rows[i]["cStatus"]);
                    }
                    cmdsql += " end   as cStatus, ";

                    cmdsql += @"cast(iTransFee as decimal(20,2)) as iTransFee,iDiscountID,cDiscountDescription,
                    cast(iDiscount as decimal(20,2)) as iDiscount,cast(iTotal as decimal(20,2)) as iTotal,
                    cast(iPrePay as decimal(20,2)) as iPrePay,cast(iARmount as decimal(20,2)) as iARmount
                    from SOPre so (nolock) inner join Customer (nolock) on so.IDCus=Customer.ID
                    inner join #tpo1 detail on so.id=detail.id
                    where so.id in (select id from #tpo) order by so.ID desc ";
                    cncmd.CommandText = cmdsql;
                    DataTable dtmain = new DataTable();
                    dtmain.Load(cncmd.ExecuteReader());

                    cmdsql = @"select sod.AutoID,sod.ID,sod.cInvCode,sod.cInvName,sod.cInvName1,sod.SKUSale,sod.iNum,
                    sod.iQuantity,sod.SKU,sod.iPriceSale,sod.iSum,
                    inv.cImgPath,inv.cImgPathLarg
                    from SODetailPre sod (nolock) left join inventory inv (nolock) on sod.cInvCode=inv.cInvCode
                    where  sod.id in (select id from #tpo) order by inv.cInvCCode,inv.iOrder ";
                    cncmd.CommandText = cmdsql;
                    DataTable dtdetail = new DataTable();
                    dtdetail.Load(cncmd.ExecuteReader());
                    _dtmain = dtmain; _dtdetail = dtdetail;

                    #endregion 5、获取订单主表与订单明细表的所有数据（ID属于3步取出的临时表）；
                }
                finally
                { cn.Close(); cn.Dispose(); }
            }
        }

        #endregion 获取订单列表（我的订单调用）

        #region 公共方法

        /// <summary>
        /// 返回订单的所有状态
        /// </summary>
        /// <returns></returns>
        private DataTable getSoStatus()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("iStatus");
            dt.Columns.Add("cStatus");

            DataRow dtr = dt.NewRow();
            dtr["iStatus"] = 99;
            dtr["cStatus"] = "";
            dt.Rows.Add(dtr);

            dtr = dt.NewRow();
            dtr["iStatus"] = 0;
            dtr["cStatus"] = "已下单";
            dt.Rows.Add(dtr);

            dtr = dt.NewRow();
            dtr["iStatus"] = 1;
            dtr["cStatus"] = "已确认";
            dt.Rows.Add(dtr);

            dtr = dt.NewRow();
            dtr["iStatus"] = 2;
            dtr["cStatus"] = "分拣中";
            dt.Rows.Add(dtr);

            dtr = dt.NewRow();
            dtr["iStatus"] = 3;
            dtr["cStatus"] = "配送中";
            dt.Rows.Add(dtr);

            dtr = dt.NewRow();
            dtr["iStatus"] = 9;
            dtr["cStatus"] = "完成";
            dt.Rows.Add(dtr);

            dtr = dt.NewRow();
            dtr["iStatus"] = -1;
            dtr["cStatus"] = "交易取消";
            dt.Rows.Add(dtr);

            return dt;
        }

        #endregion 公共方法

        //提交订单
        public override Dictionary<string, object> Save(int idcus)
        {
            NameValueCollection nvc = HttpContext.Current.Request.Form;
            string customerCouponID = (nvc["CustomerCouponID"]).GetVal_String();
            double couponAmount = 0;
            List<ReceiveCoupon> list = new List<ReceiveCoupon>();
            string receiveName; string receivePhone; string receiveAddress; string payType; List<Dictionary<string, object>> dtDetail;
            string errStr; string dPSTimeStart; string dPSTimeEnd;
            GetJsonData(out receiveName, out receivePhone, out receiveAddress, out payType, out dtDetail,
                out dPSTimeStart, out dPSTimeEnd);

            string cSoCode = string.Empty;
            using (SqlConnection cn = new SqlConnection(HandleSQL.cConnstr))
            {
                try
                {
                    SqlCommand cncmd = new SqlCommand();
                    cn.Open();
                    SqlTransaction tran = cn.BeginTransaction();
                    cncmd.Connection = cn;
                    cncmd.Transaction = tran;
                    //生成订单号
                    cSoCode = GetMaxSo(cncmd);
                    int iMaxID;
                    string tbmain; string tbdetail;
                    tbmain = "SoPre"; tbdetail = "SoDetailPre";
                    string cmdsql = "select isnull(max(id),0)+1 from " + tbmain;
                    cncmd.CommandText = cmdsql;
                    DataTable dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    if (dtjud.Rows.Count > 0)
                    {
                        iMaxID = (int)dtjud.Rows[0][0];
                    }
                    else
                    { iMaxID = 1; }
                    if (!SaveDetail_Sub(cncmd, idcus, receiveName, receivePhone, receiveAddress, payType, cSoCode, dtDetail, iMaxID, out errStr,
                        tbmain, tbdetail, dPSTimeStart, dPSTimeEnd))
                    { return ReturnValue.Get(errStr, false); }
                    // string sPromoteTable = SoPromote.GetCusPromote(cncmd, iMaxID, tbmain, tbdetail, idcus);
                    //判断优惠条件客户还能否继续享受
                    int iDisCountID = nvc["iDiscountID"].GetVal_Int();
                    string cDiscountDescription = "";
                    double dDiscount = 0;

                    #region 旧买赠

                    //if (iDisCountID != 0)
                    //{
                    //    cmdsql = string.Format("select * from {0} where autoid=@autoid ", sPromoteTable);
                    //    cncmd.CommandText = cmdsql;
                    //    cncmd.Parameters.Add(new SqlParameter("@autoid", iDisCountID));
                    //    dtjud = new DataTable();
                    //    dtjud.Load(cncmd.ExecuteReader());
                    //    if (dtjud.Rows.Count == 0)
                    //    {
                    //        return ReturnValue.Get("优惠条件已经过期,请重新回到购物车重新下单", false);
                    //    }
                    //    else
                    //    {
                    //        iDisCountID = (dtjud.Rows[0]["AutoID"]).GetVal_Int();
                    //        cDiscountDescription = (dtjud.Rows[0]["cPromoteName"]).GetVal_String();
                    //        dDiscount = (dtjud.Rows[0]["iValue"]).GetVal_Double();
                    //        cmdsql = string.Format(@"SELECT  autoid,cInvCode, iQuantity, iUnitPrice, iQuantityTotal FROM  CustomerPromoteDetail
                    //            where (iQuantityTotal>0 or iQuantityTotal=-1) and  AutoID={0}", iDisCountID);
                    //        dtjud = new DataTable();
                    //        cncmd.CommandText = cmdsql;
                    //        dtjud.Load(cncmd.ExecuteReader());
                    //        if (dtjud.Rows.Count > 0)
                    //        {
                    //            List<Dictionary<string, object>> dtpromote = new List<Dictionary<string, object>>();
                    //            for (int k = 0; k < dtjud.Rows.Count; k++)
                    //            {
                    //                Dictionary<string, object> dic = new Dictionary<string, object>();
                    //                dic.Add("tCount", dtjud.Rows[k]["iQuantity"]);
                    //                dic.Add("cInvCode", dtjud.Rows[k]["cInvCode"]);
                    //                dic.Add("iUnitPrice", dtjud.Rows[k]["iUnitPrice"]);
                    //                dic.Add("IDPromote", dtjud.Rows[k]["autoid"]);
                    //                dtpromote.Add(dic);
                    //            }
                    //            SaveSoDetail(cncmd, tbdetail, dtpromote, iMaxID, 1, idcus);
                    //        }
                    //    }
                    //}

                    #endregion 旧买赠

                    #region 新买赠

                    List<Dictionary<string, object>> dtpromote = GetPromote(cncmd, out cDiscountDescription, tbmain, tbdetail, iMaxID, idcus, out iDisCountID, out dDiscount);
                    SaveSoDetail(cncmd, tbdetail, dtpromote, iMaxID, 1, idcus);

                    #endregion 新买赠

                    double iSum = SoPromote.GetSoSum(cncmd, iMaxID, tbmain, tbdetail, idcus);
                    double iTransFee = 0;

                    //===  获取代金券  并且计算使用的代金券金额

                    couponAmount = ICoupon_V1.GetCouponsAmount(cncmd, customerCouponID, iMaxID, iSum + iTransFee - dDiscount, true);
                    if (couponAmount > 0)
                    {
                        cDiscountDescription = "现金券抵扣";
                        dDiscount = couponAmount;
                    }

                    //===
                    double iTotal = iSum + iTransFee - dDiscount;//- couponAmount
                    double iPrePay = 0;
                    double iARmount = iTotal - iPrePay;

                    cmdsql = @"
  select IDPerson from person where salecode=(
	  select  top 1 salecode from  Customer where ID  =(
			select top 1 IDCus from SOPre where ID=@id)
  )
";
                    var IDPerson = HandleSQL.GetDataObj(cmdsql, cncmd, new SqlParameter[] { new SqlParameter("@id", iMaxID) }).GetVal_String();

                    cmdsql = string.Format(@"update " + tbmain + @" set iSum={0},iTransFee={1},iDiscountID={2},cDiscountDescription='{3}',
                        iDisCount={4},iTotal={5},iPrePay={6},iARmount={7},IDPerson={9} where id={8} ",
                    iSum, iTransFee, iDisCountID, cDiscountDescription, dDiscount, iTotal, iPrePay, iARmount, iMaxID, IDPerson);
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();

                    tran.Commit();

                    #region 立减活动

                    string sql = string.Format(" exec pro_CustomerKnockactivity {0},{1},{2},'{3}',{4}", idcus, iMaxID, iSum, "", 0);
                    dtjud = new DataTable();
                    dtjud = HandleSQL.GetData(sql);

                    #endregion 立减活动

                    #region 记录商城日志

                    dtjud = new DataTable();
                    dtjud = HandleSQL.GetData(string.Format(@" exec pro_HandleSoStatusLog {0},{1},{2},'{3}' ", 0, iMaxID, 0, receiveName));

                    #endregion 记录商城日志

                    #region 发送下单通知消息

                    //获取当前用户的openid
                    //var openid = HandleWx.getCusWxOpenId(idcus);
                    var table = HandleSQL.GetData(@"SELECT TOP 1 * FROM dbo.Customer(NOLOCK) WHERE ID=@ID AND cWX IS NOT NULL", null, new SqlParameter[] { new SqlParameter("@ID", idcus) });
                    if (table.Rows != null && table.Rows.Count > 0)
                    {
                        string openid = table.Rows[0]["cWX"].GetVal_String();
                        string customerName = table.Rows[0]["storeManagerName"].GetVal_String();
                        string storeName = table.Rows[0]["storeName"].GetVal_String();
                        string address = table.Rows[0]["Province"].GetVal_String() + table.Rows[0]["City"].GetVal_String() +
                            table.Rows[0]["District"].GetVal_String() + table.Rows[0]["Street"].GetVal_String() + table.Rows[0]["Address"].GetVal_String();
                        if (!string.IsNullOrEmpty(openid) && openid.Length > 0)
                        {
                            var message = string.Format(@"订单确认\n订单号:{0}\n下单时间:" +
                                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n订单金额:{3}\n付款方式:{5}\n商户名:{1}\n收货时间:" +
                                DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 16:00前\n收货人:{4}\n收货地址:{2}\n如有疑问,请拨打4008-237-007,我们将热情为您服务,欢迎您再次光临！",
                                cSoCode, storeName, address, iTotal.ToString(), customerName, payType);
                            var returnMag = HandleWx.SendMessage(openid, message);
                            //var dic = HandleJson.GetJsonValue(returnMag);
                            //string errcode = string.Empty;
                            //if (dic.Keys.Contains("errcode"))
                            //{
                            //    errcode = string.Format("{0}", dic["errcode"]);
                            //    if (errcode != "0" && dic.Keys.Contains("errmsg"))
                            //    {
                            //        string errmsg = dic["errmsg"].GetVal_String();
                            //        if (string.IsNullOrEmpty(errmsg))
                            //        {
                            //            System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("下单通知消息:调用微信客户接口失败");
                            //        }
                            //        else
                            //        {
                            //            System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog("下单通知消息:" + errmsg);
                            //        }
                            //    }
                            //}
                        }
                    }
                    //string customerName = HandleSQL.GetDataObj(@"SELECT TOP 1 storeManagerName  FROM dbo.Customer(NOLOCK) WHERE ID=@ID", null, new SqlParameter[] { new SqlParameter("@ID", idcus) }).GetVal_String();
                    //消息内容

                    #endregion 发送下单通知消息

                    list = ICoupon_V1.GetCouponList_New(cncmd, tbmain, tbdetail, iMaxID, idcus);
                }
                finally
                { cn.Close(); cn.Dispose(); }

                //领取优惠券
                foreach (var item in list)
                    ICoupon_V1.ReceivedCoupon(idcus, item.CouponID, item.ActivityID, cSoCode);
                //返回优惠券
                return ReturnValue.Get<ReceiveCoupon>(cSoCode, list, true);
            }
        }

        #region 新获取优惠，买赠等

        /// <summary>
        /// 新获取优惠，买赠
        /// </summary>
        /// <param name="cncmd"></param>
        /// <param name="cDiscountDescription"></param>
        /// <param name="tbmain"></param>
        /// <param name="tbdetail"></param>
        /// <param name="iMaxID"></param>
        /// <param name="idcus"></param>
        /// <returns></returns>
        private List<Dictionary<string, object>> GetPromote(SqlCommand cncmd, out string cDiscountDescription, string tbmain, string tbdetail, int iMaxID, int idcus, out int iDiscountID, out double iDiscount)
        {
            List<Dictionary<string, object>> dtpromote = new List<Dictionary<string, object>>();
            cDiscountDescription = string.Empty;
            iDiscount = 0;
            iDiscountID = 0;
            string cmdsql = @"
  SELECT [ID]
  FROM[ShopWPMC].[dbo].[CustomerPromote]
  where dDateStart <= GETDATE() AND DATEADD(D,1, dDateEnd) > GETDATE()
                        ";
            var CustomerPromoteTB = HandleSQL.GetData(cmdsql, cncmd);
            for (var i = 0; i < CustomerPromoteTB.Rows.Count; i++)
            {
                cmdsql = @"
SELECT  AutoID
      , cPromoteName
      , cValue
      , cRule
      , cInvCode
      , iQuantity
      , iUnitPrice
      , iQuantityTotal
  FROM  CustomerPromoteDetail
  where ID =@ID
                        ";
                var CustomerPromoteDetailTB = HandleSQL.GetData(cmdsql, cncmd, new SqlParameter[] { new SqlParameter("@ID", CustomerPromoteTB.Rows[i][0].GetVal_Int()) });
                for (var j = 0; j < CustomerPromoteDetailTB.Rows.Count; j++)
                {
                    if (CustomerPromoteDetailTB.Rows[j][7].GetVal_Int() <= 0) break;
                    if (ICoupon_V1.IsMeetTheCondition(cncmd, tbmain, tbdetail, iMaxID, idcus, CustomerPromoteDetailTB.Rows[j][3].GetVal_String(), CustomerPromoteDetailTB.Rows[j][0].GetVal_Int()))//传入商品详情表，订单编号，活动条件返回是否对应
                    {
                        //获取赠送商品数量
                        int Count = ICoupon_V1.GetCouponCount(cncmd, tbmain, tbdetail, iMaxID, idcus, CustomerPromoteDetailTB.Rows[j][5].GetVal_String(), CustomerPromoteDetailTB.Rows[j][0].GetVal_Int());
                        //限定数量
                        if (CustomerPromoteDetailTB.Rows[j][7].GetVal_Int() < Count)
                            Count = CustomerPromoteDetailTB.Rows[j][7].GetVal_Int();
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("tCount", Count);
                        dic.Add("cInvCode", CustomerPromoteDetailTB.Rows[j]["cInvCode"]);
                        dic.Add("iUnitPrice", CustomerPromoteDetailTB.Rows[j]["iUnitPrice"]);
                        dic.Add("IDPromote", CustomerPromoteDetailTB.Rows[j]["autoid"]);
                        dtpromote.Add(dic);
                        cDiscountDescription = CustomerPromoteDetailTB.Rows[j]["cPromoteName"].GetVal_String();

                        if (iDiscount < CustomerPromoteDetailTB.Rows[j]["cValue"].GetVal_Double())
                        {
                            iDiscount = CustomerPromoteDetailTB.Rows[j]["cValue"].GetVal_Double();
                            iDiscountID = CustomerPromoteDetailTB.Rows[j]["autoid"].GetVal_Int();
                        }
                        break;
                    }
                }
            }
            return dtpromote;
        }

        #endregion 新获取优惠，买赠等

        //获取优惠
        public override Dictionary<string, object> GetPreferential(int idcus)
        {
            string receiveName; string receivePhone; string receiveAddress; string payType; List<Dictionary<string, object>> dtDetail;
            string errStr; string dPSTimeStart; string dPSTimeEnd;
            GetJsonData(out receiveName, out receivePhone, out receiveAddress, out payType, out dtDetail,
                out dPSTimeStart, out dPSTimeEnd);

            using (SqlConnection cn = new SqlConnection(HandleSQL.cConnstr))
            {
                try
                {
                    SqlCommand cncmd = new SqlCommand();
                    cn.Open();
                    SqlTransaction tran = cn.BeginTransaction();
                    cncmd.Connection = cn;
                    cncmd.Transaction = tran;
                    CreateTempTable(cncmd);
                    string cSoCode = "00001";
                    int iMaxID;
                    string tbmain; string tbdetail;
                    tbmain = "#So"; tbdetail = "#SoDetail";
                    string cmdsql = "select isnull(max(id),0)+1 from " + tbmain;
                    cncmd.CommandText = cmdsql;
                    DataTable dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    if (dtjud.Rows.Count > 0)
                    {
                        iMaxID = (int)dtjud.Rows[0][0];
                    }
                    else
                    { iMaxID = 1; }
                    if (!SaveDetail_Sub(cncmd, idcus, receiveName, receivePhone, receiveAddress, payType, cSoCode, dtDetail, iMaxID, out errStr,
                        tbmain, tbdetail, dPSTimeStart, dPSTimeEnd))
                    { return ReturnValue.Get(errStr, false); }

                    //string sPromoteTable = SoPromote.GetCusPromote(cncmd, iMaxID, tbmain, tbdetail, idcus);
                    //DataTable dtPromote = new DataTable();
                    //cmdsql = string.Format("select * from {0} order by iValue desc ", sPromoteTable);
                    //cncmd.CommandText = cmdsql;
                    //dtPromote.Load(cncmd.ExecuteReader());
                    Dictionary<string, object> dfulldata = new Dictionary<string, object>();
                    double iSum = SoPromote.GetSoSum(cncmd, iMaxID, tbmain, tbdetail, idcus);
                    double iTransFee = 0;
                    int iDiscountID = 0;
                    string cDiscountDescription = string.Empty;
                    double iDiscount = 0;
                    GetPromote(cncmd, out cDiscountDescription, tbmain, tbdetail, iMaxID, idcus, out iDiscountID, out iDiscount);

                    #region 获取立减活动信息

                    List<string> _details = new List<string>();
                    _details = (from e in dtDetail select string.Format("{0}^{1}", string.Format("{0}", e.First().Value).Split('-')[0], e.Last().Value)).ToList();
                    string _str = string.Join("#", _details.ToArray());
                    string sql = string.Format(" exec pro_CustomerKnockactivity {0},{1},{2},'{3}',{4}", idcus, 0, iSum, _str, 1);
                    dtjud = new DataTable();
                    dtjud = HandleSQL.GetData(sql);
                    if (dtjud.Rows != null && dtjud.Rows.Count > 0)
                    {
                        string _cDiscountDescription = string.Format("{0}", dtjud.Rows[0]["cDiscountDescription"]);
                        double _dDiscount = 0;
                        double.TryParse(string.Format("{0}", dtjud.Rows[0]["dDiscount"]), out _dDiscount);
                        if (_dDiscount > 0)
                        {
                            cDiscountDescription += _cDiscountDescription;
                            iDiscount += _dDiscount;
                        }
                    }

                    #endregion 获取立减活动信息

                    //if (dtPromote.Rows.Count > 0)
                    //{
                    //    iDiscountID = (int)dtPromote.Rows[0]["AutoID"];
                    //    cDiscountDescription = dtPromote.Rows[0]["cPromoteName"].ToString();
                    //    iDiscount = (double)dtPromote.Rows[0]["iValue"];
                    //}
                    //else
                    //{ iDiscountID = 0; cDiscountDescription = ""; iDiscount = 0; }

                    double iTotal = iSum + iTransFee - iDiscount;
                    double iPrePay = 0;
                    double iARmount = iTotal - iPrePay;

                    var coupons = ICoupon_V1.GetReceivedCoupons(cncmd, iTotal, idcus);
                    for (int i = 0; i < coupons.Rows.Count; i++)
                    {
                        if (coupons.Rows[i][7].GetVal_String() == "新人券")
                        {
                            iTotal -= 10;
                            iARmount -= 10;
                        }
                    }
                    dfulldata.Add("result", 1);
                    dfulldata.Add("resultdetail", "优惠条件获取成功");
                    dfulldata.Add("iSum", iSum.ToString("#,##0.00"));
                    dfulldata.Add("iTransFee", iTransFee.ToString("#,##0.00"));
                    dfulldata.Add("iDiscountID", iDiscountID);
                    dfulldata.Add("cDiscountDescription", cDiscountDescription);
                    dfulldata.Add("iDiscount", iDiscount.ToString("#,##0.00"));
                    dfulldata.Add("iTotal", iTotal.ToString("#,##0.00"));
                    dfulldata.Add("iPrePay", iPrePay.ToString("#,##0.00"));
                    dfulldata.Add("iARmount", iARmount.ToString("#,##0.00"));

                    string StarttimeList; string EndtimeList;
                    cmdsql = "select PSStart,PSEnd from OrderRange where OrderRangeTimeS<=datepart(HH, GETDATE()) and OrderRangeTimeE>=datepart(HH, GETDATE())";
                    cncmd.CommandText = cmdsql;
                    dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    StarttimeList = (dtjud.Rows[0]["PSStart"]).GetVal_String();
                    dfulldata.Add("StarttimeList", StarttimeList);
                    EndtimeList = (dtjud.Rows[0]["PSEnd"]).GetVal_String();
                    dfulldata.Add("EndtimeList", EndtimeList);

                    cmdsql = string.Format("select dPSTimeStart,dPSTimeEnd from Customer where ID={0} ", idcus);
                    cncmd.CommandText = cmdsql;
                    dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    string dPSTimeStart1 = ""; string dPSTimeEnd1 = "";
                    if (dtjud.Rows.Count > 0)
                    {
                        dPSTimeStart1 = (dtjud.Rows[0]["dPSTimeStart"]).GetVal_String();
                        dPSTimeEnd1 = (dtjud.Rows[0]["dPSTimeEnd"]).GetVal_String();
                    }

                    string[] sstart = StarttimeList.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    if (Array.IndexOf(sstart, dPSTimeStart1) == -1)
                    {
                        dPSTimeStart1 = sstart[0];
                    }
                    string[] ssend = EndtimeList.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    if (Array.IndexOf(ssend, dPSTimeEnd1) == -1)
                    {
                        dPSTimeEnd1 = ssend[0];
                    }
                    dfulldata.Add("dPSTimeStart", dPSTimeStart1);
                    dfulldata.Add("dPSTimeEnd", dPSTimeEnd1);
                    dfulldata.Add("CouponsRows", coupons.Rows.Count);
                    dfulldata.Add("CouponsDetail", coupons.ToList());
                    dfulldata.Add("MaxCouponAmount", (int)(iTotal * 0.05));//返回最大可以使用优惠金额
                    tran.Rollback();
                    return dfulldata;
                }
                finally
                {
                    cn.Close();
                    cn.Dispose();
                }
            }
        }

        //选中使用优惠券
        public override Dictionary<string, object> SelectedCoupon(int idcus)
        {
            NameValueCollection nvc = HttpContext.Current.Request.Form;

            string customerCouponID = (nvc["CustomerCouponID"]).GetVal_String();
            double couponAmount = 0;
            string receiveName; string receivePhone; string receiveAddress; string payType; List<Dictionary<string, object>> dtDetail;
            string errStr; string dPSTimeStart; string dPSTimeEnd;
            GetJsonData(out receiveName, out receivePhone, out receiveAddress, out payType, out dtDetail,
                out dPSTimeStart, out dPSTimeEnd);
            using (SqlConnection cn = new SqlConnection(HandleSQL.cConnstr))
            {
                try
                {
                    SqlCommand cncmd = new SqlCommand();
                    cn.Open();
                    SqlTransaction tran = cn.BeginTransaction();
                    cncmd.Connection = cn;
                    cncmd.Transaction = tran;
                    CreateTempTable(cncmd);
                    string cSoCode = "00001";
                    int iMaxID;
                    string tbmain; string tbdetail;
                    tbmain = "#So"; tbdetail = "#SoDetail";

                    string cmdsql = "select isnull(max(id),0)+1 from " + tbmain;
                    cncmd.CommandText = cmdsql;
                    DataTable dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    if (dtjud.Rows.Count > 0)
                    {
                        iMaxID = (int)dtjud.Rows[0][0];
                    }
                    else
                    { iMaxID = 1; }
                    if (!SaveDetail_Sub(cncmd, idcus, receiveName, receivePhone, receiveAddress, payType, cSoCode, dtDetail, iMaxID, out errStr,
                        tbmain, tbdetail, dPSTimeStart, dPSTimeEnd))
                    { return ReturnValue.Get(errStr, false); }
                    //string sPromoteTable = SoPromote.GetCusPromote(cncmd, iMaxID, tbmain, tbdetail, idcus);
                    //DataTable dtPromote = new DataTable();
                    //cmdsql = string.Format("select * from {0} order by iValue desc ", sPromoteTable);
                    //cncmd.CommandText = cmdsql;
                    //dtPromote.Load(cncmd.ExecuteReader());
                    Dictionary<string, object> dfulldata = new Dictionary<string, object>();
                    double iSum = SoPromote.GetSoSum(cncmd, iMaxID, tbmain, tbdetail, idcus);
                    double iTransFee = 0;
                    int iDiscountID = 0;
                    string cDiscountDescription = string.Empty;
                    double iDiscount = 0;
                    GetPromote(cncmd, out cDiscountDescription, tbmain, tbdetail, iMaxID, idcus, out iDiscountID, out iDiscount);
                    //if (dtPromote.Rows.Count > 0)
                    //{
                    //    iDiscountID = (int)dtPromote.Rows[0]["AutoID"];
                    //    cDiscountDescription = dtPromote.Rows[0]["cPromoteName"].ToString();
                    //    iDiscount = (double)dtPromote.Rows[0]["iValue"];
                    //}
                    //else
                    //{ iDiscountID = 0; cDiscountDescription = ""; iDiscount = 0; }

                    //===  获取代金券   不使用

                    couponAmount = ICoupon_V1.GetCouponsAmount(cncmd, customerCouponID, iMaxID, iSum + iTransFee - iDiscount, false);
                    //===
                    double iTotal = iSum + iTransFee - iDiscount - couponAmount;
                    double iPrePay = 0;
                    double iARmount = iTotal - iPrePay;
                    dfulldata.Add("result", 1);
                    dfulldata.Add("resultdetail", "优惠条件获取成功");
                    dfulldata.Add("iSum", iSum.ToString("#,##0.00"));
                    dfulldata.Add("iTransFee", iTransFee.ToString("#,##0.00"));
                    dfulldata.Add("iDiscountID", iDiscountID);
                    dfulldata.Add("cDiscountDescription", cDiscountDescription);
                    dfulldata.Add("iDiscount", iDiscount.ToString("#,##0.00"));
                    dfulldata.Add("iTotal", iTotal.ToString("#,##0.00"));
                    dfulldata.Add("iPrePay", iPrePay.ToString("#,##0.00"));
                    dfulldata.Add("iARmount", iARmount.ToString("#,##0.00"));

                    string StarttimeList; string EndtimeList;
                    cmdsql = "select PSStart,PSEnd from OrderRange where OrderRangeTimeS<=datepart(HH, GETDATE()) and OrderRangeTimeE>=datepart(HH, GETDATE())";
                    cncmd.CommandText = cmdsql;
                    dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    StarttimeList = dtjud.Rows[0]["PSStart"].GetVal_String();
                    dfulldata.Add("StarttimeList", StarttimeList);
                    EndtimeList = dtjud.Rows[0]["PSEnd"].GetVal_String();
                    dfulldata.Add("EndtimeList", EndtimeList);

                    cmdsql = string.Format("select dPSTimeStart,dPSTimeEnd from Customer where ID={0} ", idcus);
                    cncmd.CommandText = cmdsql;
                    dtjud = new DataTable();
                    dtjud.Load(cncmd.ExecuteReader());
                    string dPSTimeStart1 = ""; string dPSTimeEnd1 = "";
                    if (dtjud.Rows.Count > 0)
                    {
                        dPSTimeStart1 = dtjud.Rows[0]["dPSTimeStart"].GetVal_String();
                        dPSTimeEnd1 = dtjud.Rows[0]["dPSTimeEnd"].GetVal_String();
                    }

                    string[] sstart = StarttimeList.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    if (Array.IndexOf(sstart, dPSTimeStart1) == -1)
                    {
                        dPSTimeStart1 = sstart[0];
                    }
                    string[] ssend = EndtimeList.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    if (Array.IndexOf(ssend, dPSTimeEnd1) == -1)
                    {
                        dPSTimeEnd1 = ssend[0];
                    }
                    dfulldata.Add("dPSTimeStart", dPSTimeStart1);
                    dfulldata.Add("dPSTimeEnd", dPSTimeEnd1);
                    var coupons = ICoupon_V1.GetReceivedCoupons(cncmd, iSum + iTransFee - iDiscount, idcus);
                    dfulldata.Add("CouponsRows", coupons.Rows.Count);
                    dfulldata.Add("CouponsDetail", coupons.ToList());
                    dfulldata.Add("MaxCouponAmount", (int)(iTotal * 0.05));//返回最大可以使用优惠金额
                    tran.Rollback();
                    return dfulldata;
                }
                finally
                {
                    cn.Close();
                    cn.Dispose();
                }
            }
        }

        private void GetJsonData(
          out string _receiveName, out string _receivePhone, out string _receiveAddress,
          out string _payType, out List<Dictionary<string, object>> listdetail,
          out string dPSTimeStart, out string dPSTimeEnd)
        {
            NameValueCollection nvc = HttpContext.Current.Request.Form;
            _receiveName = (nvc["ReviceName"]).GetVal_String();
            _receivePhone = (nvc["RevicePhoto"]).GetVal_String();
            _receiveAddress = (nvc["ReviceAdress"]).GetVal_String();
            _payType = (nvc["PayType"]).GetVal_String();
            dPSTimeStart = (nvc["dPSTimeStart"]).GetVal_String();
            dPSTimeEnd = (nvc["dPSTimeEnd"]).GetVal_String();
            listdetail = nvc.GetList("data");
            //_dtDetail = new DataTable();
            //_dtDetail.Columns.Add("tCount", typeof(float));
            //_dtDetail.Columns.Add("cInvCode", typeof(string));
            //_dtDetail = nvc.GetListToDataTable("data", _dtDetail);
        }

        private string GetMaxSo(SqlCommand cncmd)
        {
            long iSOCode = 0;
            string cmdsql = string.Format("select isnull(max(cSoCode),0) from SoPre ");
            DataTable dt = HandleSQL.GetData(cmdsql, cncmd);
            if (dt.Rows.Count > 0)
            {
                iSOCode = dt.Rows[0][0].GetVal_Int();
            }
            if (iSOCode == 0)
            { iSOCode = 10001; }
            else
            { iSOCode += 1; }
            return iSOCode.ToString();
        }

        private bool SaveDetail_Sub(SqlCommand cncmd, int cusid, string _reviceName, string _revicePhone, string _reviceAdress, string _payType,
          string _cSoCode, List<Dictionary<string, object>> dtDetail, int _iMaxID,
          out string _errStr, string _tbmain, string _tbdetail, string dPSTimeStart, string dPSTimeEnd)
        {
            CustomerINFO cusInfo = ICustomer_V1.GetCusInfo(cusid);
            string cmdsql = @"select IDOrderRange from OrderRange where OrderRangeTimeS<=datepart(HH, GETDATE()) and OrderRangeTimeE>=datepart(HH, GETDATE())";
            cncmd.CommandText = cmdsql;
            //下单区间ID
            int IDOrderRange = cncmd.ExecuteScalar().GetVal_Int();
            cmdsql = @"insert into " + _tbmain + @"(ID,IDCus,cSoCode,cPayCode,iSum,iSumPay,dPSDate,cSHCus,cSHDZ,cSHR,cSHMobile,dDate,cFromIP,iStatus,dMDate,dPSTimeStart,dPSTimeEnd,IDOrderRange)
                    values(@ID,@IDCus,@cSoCode,@cPayCode,0,0,@dPSDate,@cSHCus,@cSHDZ,@cSHR,@cSHMobile,convert(nvarchar,getdate(),23),@cFromIP,0,getdate(),@dPSTimeStart,@dPSTimeEnd,@IDOrderRange)";
            cncmd.CommandText = cmdsql;
            cncmd.Parameters.Add(new SqlParameter("@ID", _iMaxID));
            cncmd.Parameters.Add(new SqlParameter("@IDCus", cusInfo.IDCus));
            cncmd.Parameters.Add(new SqlParameter("@cSoCode", _cSoCode));
            cncmd.Parameters.Add(new SqlParameter("@dPSDate", DateTime.Now));
            cncmd.Parameters.Add(new SqlParameter("@cSHCus", cusInfo.mobile));
            cncmd.Parameters.Add(new SqlParameter("@cSHDZ", _reviceAdress));
            cncmd.Parameters.Add(new SqlParameter("@cSHR", _reviceName));
            cncmd.Parameters.Add(new SqlParameter("@cSHMobile", _revicePhone));
            cncmd.Parameters.Add(new SqlParameter("@cFromIP", HandleLog.GetIPAddress()));
            cncmd.Parameters.Add(new SqlParameter("@cPayCode", _payType));
            cncmd.Parameters.Add(new SqlParameter("@dPSTimeStart", dPSTimeStart));
            cncmd.Parameters.Add(new SqlParameter("@dPSTimeEnd", dPSTimeEnd));
            cncmd.Parameters.Add(new SqlParameter("@IDOrderRange", IDOrderRange));
            cncmd.ExecuteNonQuery();
            cncmd.Parameters.Clear();

            if (_tbmain.Substring(0, 1) != "#")
            {
                if (dPSTimeStart.Length > 0 && dPSTimeEnd.Length > 0)
                {
                    cmdsql = "update customer set dPSTimeStart=@dPSTimeStart,dPSTimeEnd=@dPSTimeEnd where id=@id";
                    cncmd.CommandText = cmdsql;
                    cncmd.Parameters.Add(new SqlParameter("@dPSTimeStart", dPSTimeStart));
                    cncmd.Parameters.Add(new SqlParameter("@dPSTimeEnd", dPSTimeEnd));
                    cncmd.Parameters.Add(new SqlParameter("@ID", cusInfo.IDCus));
                    cncmd.ExecuteNonQuery();
                    cncmd.Parameters.Clear();
                }
            }
            //                cmdsql = @"insert into " + _tbdetail + @"(ID,cInvCode,iQuantity)
            //                        values(@ID,@cInvCode,@iQuantity)";
            //                cncmd.CommandText = cmdsql;
            //                cncmd.Parameters.Add("@ID", SqlDbType.Int);
            //                cncmd.Parameters.Add("@cInvCode", SqlDbType.NVarChar, 50);
            //                cncmd.Parameters.Add("@iQuantity", SqlDbType.Float);
            //                int irowSave = 0;
            //                for (int i = 0; i < _dtDetail.Rows.Count; i++)
            //                {
            //                    double iQuantity = Common.handleSQL.getValueDbl(_dtDetail.Rows[i]["tCount"]);
            //                    if (iQuantity >= 0.01)
            //                    {
            //                        cncmd.Parameters["@ID"].Value = _iMaxID;
            //                        cncmd.Parameters["@cInvCode"].Value = _dtDetail.Rows[i]["cInvCode"];
            //                        cncmd.Parameters["@iQuantity"].Value = iQuantity;
            //                        cncmd.ExecuteNonQuery();
            //                        irowSave += 1;
            //                    }
            //                }
            //                cncmd.Parameters.Clear();
            //                if (irowSave == 0)
            //                { _errStr = "没有找到需要保存的信息"; return false; }
            //                cmdsql = string.Format(@"update  {0} set iUnitPrice=i.iUnitPrice,iSum=round(iQuantity*i.iUnitPrice,2),
            //cInvName=i.cInvName,cInvName1=i.cInvName1,cDesc=i.cDesc,cDW=i.cDW,iBZ=i.iBZ,
            //cBZGG = i.cBZGG,cBZGGSM = i.cBZGGSM,cCX = i.cCX,cXQ = i.cXQ from Inventory i
            //            where {0}.cInvCode = i.cInvCode and {0}.ID=" + _iMaxID.ToString(), _tbdetail);
            //                cncmd.CommandText = cmdsql;
            //                cncmd.ExecuteNonQuery();
            _errStr = SaveSoDetail(cncmd, _tbdetail, dtDetail, _iMaxID, 0, cusid);
            if (_errStr.Length > 0) { return false; }
            //判断总金额是否够
            DataTable dtjud;
            double isominmoney = GetConfig("SoMinMoney").GetVal_Double();
            if (isominmoney > 0)
            {
                cmdsql = string.Format("select isnull(SUM(iSum),0) from {0} where ID in (select ID from {1} where IDCus={2} and iStatus=0) ",
                    _tbdetail, _tbmain, cusInfo.IDCus);
                cncmd.CommandText = cmdsql;
                dtjud = new DataTable();
                dtjud.Load(cncmd.ExecuteReader());
                if (dtjud.Rows.Count > 0)
                {
                    double dtsomoney = dtjud.Rows[0][0].GetVal_Double();
                    //如果为临时表，加上主表的金额
                    if (_tbmain.Substring(0, 1) == "#")
                    {
                        cmdsql = string.Format("select isnull(SUM(iSum), 0) from SODetailPre where ID in (select ID from SOPre where IDCus = {0} and iStatus = 0) ",
                     cusInfo.IDCus);
                        cncmd.CommandText = cmdsql;
                        dtsomoney = dtsomoney + (cncmd.ExecuteScalar()).GetVal_Double();
                    }
                    if (dtsomoney < isominmoney)
                    { _errStr = "未达到订单的最低金额" + isominmoney.ToString(); return false; }
                }
            }
            //检查是否满足限购条件
            cmdsql = @"if(OBJECT_ID('tempdb..#sodd') is not null) drop table #sodd ";
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            if (_tbmain.Substring(0, 1) == "#")
            {
                cmdsql = string.Format(@"
select cInvCode,cInvCodeSub,sum(iNum) as iNum into #sodd from
(select cinvcode,cInvCodeSub,iNum from SOPre inner join SODetailPre
on sopre.ID=sodetailpre.ID
where iStatus=0 and IDCus={0}
union
select cinvcode,cInvCodeSub,iNum from #SO SOPre inner join #SODetail SODetailPre
on sopre.ID=sodetailpre.ID) t group by cInvCode,cInvCodeSub", cusInfo.IDCus);
            }
            else
            {
                cmdsql = string.Format(@"select cinvcode,cInvCodeSub,SUM(iNum) as iNum into #sodd from SOPre inner join SODetailPre
on sopre.ID=sodetailpre.ID
where iStatus=0 and IDCus={0}
group by cInvCode,cInvCodeSub ", cusInfo.IDCus);
            }
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            cmdsql = @"select t.cInvCode,t.cInvCodeSub,i.cInvName,i.iXG,i.cDW from #sodd t inner join inventorySale i
on t.cInvCode = i.cInvCode and t.cInvCodeSub=i.cInvCodeSub and t.iNum > ISNULL(i.iXG, 0) and ISNULL(i.iXG, 0)<> 0 ";
            cncmd.CommandText = cmdsql;
            dtjud = new DataTable();
            dtjud.Load(cncmd.ExecuteReader());
            string errs = "";
            if (dtjud.Rows.Count > 0)
            {
                for (int i = 0; i < dtjud.Rows.Count; i++)
                {
                    errs += dtjud.Rows[i]["cInvName"].GetVal_String() + "限购" + (dtjud.Rows[i]["iXG"]).GetVal_String()
                        + (dtjud.Rows[i]["cDW"]).ToString() + Environment.NewLine;
                }
                _errStr += "不满足限购条件：<BR>" + errs + "<BR>请明天再来下单";
                return false;
            }
            //判断产品是否停用
            cmdsql = string.Format(@"select so.cInvCode,so.cInvCodeSub,invsale.cInvName,isnull(invsale.iStatus,0) as iStatus from {0} so left join InventorySale invsale
on (so.cInvCode = invsale.cInvCode  and so.cInvCodeSub = invsale.cInvCodeSub) where so.id={1}", _tbdetail, _iMaxID);
            cncmd.CommandText = cmdsql;
            dtjud = new DataTable();
            dtjud.Load(cncmd.ExecuteReader());

            errs = "";
            for (int i = 0; i < dtjud.Rows.Count; i++)
            {
                if ((dtjud.Rows[i]["iStatus"]).GetVal_Int() == 1)
                {
                    errs += "产品[" + (dtjud.Rows[i]["cInvCode"]).GetVal_String() + "-" +
                         (dtjud.Rows[i]["cInvCodeSub"]).ToString() + "]" +
                         (dtjud.Rows[i]["cInvName"]).ToString() + "已经停止销售<BR>";
                }
            }
            if (errs.Length > 0)
            {
                _errStr = "部分产品已经停止销售" + errs + "请清空购物车后重新下单";
                return false;
            }

            //扣减库存
            cmdsql = string.Format(@"update invs set iCK=isnull(invs.iCK,0)+sod.iQuantity from InventoryStore invs inner join
(select cInvCode,sum(iQuantity) as iQuantity from {0} where id={1} group by cInvCode) sod
on invs.cInvCode = sod.cInvCode ", _tbdetail, _iMaxID);
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            //判断库存是否足够
            cmdsql = string.Format(@" select i.cInvCode,sod.cInvName,sod.cInvName1,sod.SKU,
i.iKY+sod.iQuantity as KC,sod.iQuantity from InventoryStore i
inner join
(select cInvCode, sum(iQuantity) as iQuantity,max(cInvName) as cInvName,max(cInvName1) as cInvName1,max(SKU) as SKU,max(iConverRate) as iConverRate from {0} where ID = {1} group by cInvCode) sod
on i.cInvCode = sod.cInvCode
where iKY < -0.01  ", _tbdetail, _iMaxID);
            cncmd.CommandText = cmdsql;
            dtjud = new DataTable();
            dtjud.Load(cncmd.ExecuteReader());

            for (int i = 0; i < dtjud.Rows.Count; i++)
            {
                errs += "【" + (dtjud.Rows[0]["cInvName"]).ToString() + "|" + (dtjud.Rows[0]["cInvName1"]).ToString() +
                      "】库存只剩余" + (dtjud.Rows[0]["KC"]).ToString() + (dtjud.Rows[0]["SKU"]).ToString() +
                      "你下单" + (dtjud.Rows[0]["iQuantity"]).ToString() + "，库存不足呢<BR>";
                System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog(errs);
                //+"本单" + Common.handleOBJ.toString(dtjud.Rows[0]["iQuantity"]) + Environment.NewLine;
            }
            if (errs.Length > 0)
            { _errStr = "库存不足<BR>" + errs; return false; }
            _errStr = "";

            //判断销售数量是否超过
            cmdsql = string.Format(@"update invsale set iSaleQuantity=iSaleQuantity-iNum from
(select cInvCode,cInvCodeSub,SUM(iNum) as iNum from {0} where ID={1} group by cInvCode,cInvCodeSub)
 so inner join InventorySale invsale
on (so.cInvCode=invsale.cInvCode and so.cInvCodeSub=invsale.cInvCodeSub)
where invsale.iControlSale=1", _tbdetail, _iMaxID);
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            cmdsql = string.Format(@"select distinct invsale.cInvName,invsale.cInvName1,invsale.iSaleQuantity+so.iNum as kc,invsale.cDW,so.iNum from InventorySale invsale inner join SODetailPre so on (invsale.cInvCode=so.cInvCode and invsale.cInvCodeSub=so.cInvCodeSub)
where iControlSale=1 and iSaleQuantity<-0.01");
            cncmd.CommandText = cmdsql;
            dtjud = new DataTable();
            dtjud.Load(cncmd.ExecuteReader());
            for (int i = 0; i < dtjud.Rows.Count; i++)
            {
                errs += "【" + (dtjud.Rows[0]["cInvName"]).GetVal_String() + "|" + (dtjud.Rows[0]["cInvName1"]).GetVal_String() +
                      "】可下单数量为" + (dtjud.Rows[0]["kc"]).GetVal_String() + (dtjud.Rows[0]["cDW"]).GetVal_String() +
                      "你下单" + (dtjud.Rows[0]["iNum"]).GetVal_String() + "，已经超限<BR>";
                System.Reflection.MethodBase.GetCurrentMethod().WriteErrLog(errs);
                //+"本单" + Common.handleOBJ.toString(dtjud.Rows[0]["iQuantity"]) + Environment.NewLine;
            }
            if (errs.Length > 0)
            { _errStr = "下单数量超限<BR>" + errs; return false; }
            _errStr = "";

            return true;
        }

        private string SaveSoDetail(SqlCommand cncmd, string _tbdetail, List<Dictionary<string, object>> dtDetail, int _iMaxID, int bCX,
          int idcus)
        {
            string cmdsql = @"insert into " + _tbdetail + @"(ID,cInvCode,cInvCodeSub,iNum,bCX)
                        values(@ID,@cInvCode,@cInvCodeSub,@iNum,@bCX)";
            cncmd.CommandText = cmdsql;
            cncmd.Parameters.Add("@ID", SqlDbType.Int);
            cncmd.Parameters.Add("@cInvCode", SqlDbType.NVarChar, 50);
            cncmd.Parameters.Add("@cInvCodeSub", SqlDbType.NVarChar, 50);
            cncmd.Parameters.Add("@iNum", SqlDbType.Float);
            cncmd.Parameters.Add("@bCX", SqlDbType.Int);
            if (bCX == 1)
            {
                cmdsql = @"insert into " + _tbdetail + @"(ID,cInvCode,cInvCodeSub,iNum,bCX,iPriceSale,IDPromote)
                        values(@ID,@cInvCode,@cInvCodeSub,@iNum,@bCX,@iPriceSale,@IDPromote)";
                cncmd.CommandText = cmdsql;
                cncmd.Parameters.Add("@iPriceSale", SqlDbType.Float);
                cncmd.Parameters.Add("@IDPromote", SqlDbType.Int);
            }
            int irowSave = 0;
            for (int i = 0; i < dtDetail.Count; i++)
            {
                double iQuantity = (dtDetail[i]["tCount"]).GetVal_Double();
                if (iQuantity >= 0.01)
                {
                    cncmd.Parameters["@ID"].Value = _iMaxID;
                    string cinvcode_all = (dtDetail[i]["cInvCode"]).GetVal_String();
                    string[] cinv = cinvcode_all.Split("-".ToArray());
                    //string cinvcode
                    string cInvCode = "";
                    string cInvCodeSub = "";
                    if (cinv.Length >= 2)
                    {
                        cInvCode = cinv[0];
                        cInvCodeSub = cinv[1];
                    }
                    else
                    { cInvCode = cinvcode_all; cInvCodeSub = ""; }
                    cncmd.Parameters["@cInvCode"].Value = cInvCode;
                    cncmd.Parameters["@cInvCodeSub"].Value = cInvCodeSub;
                    cncmd.Parameters["@iNum"].Value = iQuantity;
                    cncmd.Parameters["@bCX"].Value = bCX;
                    if (bCX == 1)
                    {
                        cncmd.Parameters["@iPriceSale"].Value = dtDetail[i]["iUnitPrice"];
                        cncmd.Parameters["@IDPromote"].Value = dtDetail[i]["IDPromote"];
                    }
                    cncmd.ExecuteNonQuery();
                    irowSave += 1;
                }
            }
            cncmd.Parameters.Clear();
            if (irowSave == 0)
            { return "没有找到需要保存的信息"; }
            if (bCX == 1)
            {
                cmdsql = string.Format(@"update  {0} set iSum=round(iQuantity*{0}.iUnitPrice,2),
cInvName=i.cInvName,cInvName1='优惠赠送',SKUSale=i.cDW,iConverRate=1,iConverDiscount=0,
iQuantity=iNum
 from Inventory i
            where bCX=1 and {0}.cInvCode = i.cInvCode and {0}.ID=" + _iMaxID.ToString(), _tbdetail);
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();

                cmdsql = string.Format(@"update so set cInvName=isnull(invsale.cInvName,inv.cInvName),
cInvName1 ='优惠赠送',SKUSale=isnull(invsale.cDW,inv.cDW),
iConverRate=isnull(invsale.iConverRate,1),iConverDiscount=isnull(invsale.iConverDiscount,0),
iQuantity=iNum*isnull(invsale.iConverRate,1),iUnitPrice=iPriceSale/isnull(invsale.iConverRate,1),iSum=iNum*so.iPriceSale,
SKU=inv.cDW
from {0} so left join  InventorySale invsale on so.cInvCode=invsale.cInvCode and so.cInvCodeSub=invsale.cInvCodeSub
left join Inventory inv on so.cInvCode=inv.cInvCode
where bCX=1 and so.ID=" + _iMaxID.ToString(), _tbdetail);
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();
            }
            else
            {
                cmdsql = "if (object_id('tempdb..#tinv') is not null) drop table #tinv";
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();
                cmdsql = "create table #tinv(cInvCode nvarchar(200))";
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();
                cmdsql = string.Format("insert into #tinv(cInvCode)select cInvCode+'-'+cInvCodeSub from {0} where id={1}",
                    _tbdetail, _iMaxID);
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();

                cmdsql = "if (object_id('tempdb..#tprice') is not null) drop table #tprice";
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();
                cmdsql = "create table #tprice(cInvCode nvarchar(200),iUnitPrice float,iSalePrice float)";
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();
                //计算价格
                cncmd.CommandText = string.Format("exec  getInventoryPrice {0},'{1}','{2}'", idcus, "#tinv", "#tprice");
                cncmd.ExecuteNonQuery();
                cmdsql = string.Format(@"select cInvCode+'-'+cInvCodeSub + '|' +cInvName+'|'+cInvName1 as cInvName from InventorySale
                    where cInvCode+'-'+cInvCodeSub in (
                    select so.cInvCode+'-'+so.cInvCodeSub  from {0} so
                    where so.id ={1} and so.cInvCode+'-'+so.cInvCodeSub not in (select cInvCode from #tprice)
                    )", _tbdetail, _iMaxID);
                cncmd.CommandText = cmdsql;
                DataTable dtcusjud = new DataTable();
                dtcusjud.Load(cncmd.ExecuteReader());
                if (dtcusjud.Rows.Count > 0)
                {
                    string errstr = "";
                    for (int i = 0; i < dtcusjud.Rows.Count; i++)
                    {
                        errstr += (dtcusjud.Rows[i][0]).GetVal_String();
                    }
                    errstr += "在当前的时间不售卖，请先在购物车上删除！";
                    return errstr;
                }

                cmdsql = string.Format(@"update so set iPriceSale=t.iSalePrice from {0} so,#tprice t
                        where so.cInvCode+'-'+so.cInvCodeSub=t.cInvCode and so.id ={1}", _tbdetail, _iMaxID);
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();

                cmdsql = string.Format(@"update so set cInvName=invsale.cInvName,cInvName1 =invsale.cInvName1,SKUSale=invsale.cDW,
iConverRate=invsale.iConverRate,iConverDiscount=invsale.iConverDiscount,
iQuantity=iNum*invsale.iConverRate,iUnitPrice=iPriceSale/invsale.iConverRate,iSum=iNum*iPriceSale,
SKU=inv.cDW
from {0} so left join  InventorySale invsale on so.cInvCode=invsale.cInvCode and so.cInvCodeSub=invsale.cInvCodeSub
left join Inventory inv on so.cInvCode=inv.cInvCode
where bCX=0 and so.ID=" + _iMaxID.ToString(), _tbdetail);
                cncmd.CommandText = cmdsql;
                cncmd.ExecuteNonQuery();
                //                cmdsql = string.Format(@"update {0} set iUnitPrice=i.iUnitPrice,iSum=round(iQuantity*i.iUnitPrice,2),
                //cInvName=i.cInvName,cInvName1=i.cInvName1,cDesc=i.cDesc,cDW=i.cDW,iBZ=i.iBZ,
                //cBZGG = i.cBZGG,cBZGGSM = i.cBZGGSM,cCX = i.cCX,cXQ = i.cXQ from Inventory i
                //            where bCX=0 and {0}.cInvCode = i.cInvCode and {0}.ID=" + _iMaxID.ToString(), _tbdetail);
            }

            //扣减促销品数量
            if (bCX == 1)
            {
                if (_tbdetail.Substring(0, 1) != "#")
                {
                    //cmdsql = string.Format(@"update CustomerPromoteDetail set iQuantityTotal=iQuantityTotal-{0}
                    // where AutoID in (select idPromote  from SODetailPre where bCX = 1 and id ={1})", iQuantity.ToString(), _iMaxID.ToString());

                    cmdsql = string.Format(@"  update CustomerPromoteDetail   set iQuantityTotal=iQuantityTotal-temp.iQuantity
  from (select idPromote,iQuantity  from SODetailPre where bCX = 1 and id ={0}) as temp
   where   AutoID = temp.idPromote", _iMaxID.ToString());
                    cncmd.CommandText = cmdsql;
                    cncmd.ExecuteNonQuery();
                }
            }

            return "";
        }

        private void CreateTempTable(SqlCommand cncmd)
        {
            string cmdsql = @"if(OBJECT_ID('tempdb..#so') is not null) drop table #so ";
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            cmdsql = @"select * into #so from soPre where 1=0";
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            cmdsql = @"if(OBJECT_ID('tempdb..#SODetail') is not null) drop table #SODetail ";
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
            cmdsql = @"select * into #SoDetail from sodetailPre where 1=0";
            cncmd.CommandText = cmdsql;
            cncmd.ExecuteNonQuery();
        }

        public string GetConfig(string configName)
        {
            string cmdsql = "select cValue from ShopConfig (nolock) where cEngName=@cEngName";
            DataTable dt = HandleSQL.GetData(cmdsql, null, new SqlParameter[] { new SqlParameter("@cEngName", configName) });
            string sReturn = "";
            if (dt.Rows.Count > 0)
            {
                sReturn = (dt.Rows[0][0]).GetVal_String();
            }
            return sReturn;
        }

        public override bool IsServiceTime()
        {
            string cmdsql = "select top 1 IDOrderRange from OrderRange where OrderRangeTimeS<=datepart(HH, GETDATE()) and OrderRangeTimeE>datepart(HH, GETDATE())";
            DataTable dtjud = HandleSQL.GetData(cmdsql);
            if (dtjud.Rows.Count == 0)
            {
                return false;
            }
            return true;
        }

        #region 订单日志跟踪记录

        public override Dictionary<string, object> HlSoStatusLog()
        {
            StringBuilder sql = new StringBuilder();
            NameValueCollection nv = HttpContext.Current.Request.QueryString;

            #region 界面值处理

            int id = 0;
            int.TryParse(nv["id"], out id); //商城订单
            //string code = string.Format("{0}", nv["code"]);//操作码 0 新增  1 ： 查询
            if (id <= 0)
            {
                return Common.ReturnValue.Get("商城订单消息错误", false);
            }

            #endregion 界面值处理

            #region SQL语句

            sql.Append(string.Format(@" exec pro_HandleSoStatusLog {0},{1},NULL,'{2}' ", 1, id, ""));

            #endregion SQL语句

            #region 执行语句

            var dt = Common.HandleSQL.GetData(sql.ToString());
            if (dt.Rows == null || dt.Rows.Count == 0)
            {
                return Common.ReturnValue.Get("没有数据", false);
            }
            else
            {
                var dic = Common.ReturnValue.Get("获取数据成功", true);
                dic.Add("details", HandleJson.ToJson_sub(dt));
                return dic;
            }

            #endregion 执行语句
        }

        #endregion 订单日志跟踪记录
    }
}